use diesel::{prelude::{Insertable, Queryable}, query_dsl::methods::FilterDsl, Connection, ExpressionMethods, RunQueryDsl, SqliteConnection};

diesel::table! {
    global_config {
        id -> Integer,
        proxy -> Text,
        worker_num -> Integer,
        combine_type -> Integer
    }
}

// src/models.rs
#[derive(Queryable, Insertable, Debug)]
#[diesel(table_name = global_config)]
 struct GlobalConfig {
    pub proxy: String,
    pub worker_num: i32,
    pub combine_type: i32,
}
#[derive(Queryable, Debug)]
#[diesel(table_name = global_config)]
 struct QueryGlobalConfig {
    pub id: i32,
    pub proxy: String,
    pub worker_num: i32,
    pub combine_type: i32,
}

pub fn establish_connection() -> SqliteConnection {
    let database_url = "local.db";
    SqliteConnection::establish(&database_url)
        .expect("Failed to connect to database")
}

#[test]
pub fn test() -> Result<(),Box<dyn std::error::Error>>{
    let mut connection = establish_connection();
    // 插入数据
    // 不支持通过代码创建表，还要通过数据库工具 diesel_client 创建
    diesel::insert_into(global_config::table)
        .values(&GlobalConfig { 
            proxy: "Bob".to_string(), 
            worker_num: 35 ,
            combine_type: 2 ,
        })
        .execute(&mut connection)?;

    // 查询数据
    let results = global_config::table
        .filter(global_config::proxy.eq("Bob"))
        .load::<QueryGlobalConfig>(&mut connection)?;
    println!("results: {:?}", results);
    Ok(())
}